package xyz.labmem.main.application.controller.api.sys.log;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.labmem.main.annotation.RoleValid;
import xyz.labmem.main.application.controller.api.sys.log.request.LoginLogRequest;
import xyz.labmem.main.application.entity.sys.LoginLogs;
import xyz.labmem.main.result.ResultUtil;
import xyz.labmem.main.result.ResultVo;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author ：刘天予
 * @date ：Created in 2020/6/24 11:13
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
@Api(tags = "登录日志API")
@RequestMapping("/admin/loginLog/api")
public class LoginLogApi {

    private final MongoTemplate mongoTemplate;

    public LoginLogApi(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * @return
     */
    @PostMapping("/list")
    @RoleValid
    @ApiOperation("日志列表")
    public ResultVo authorityList(@RequestBody LoginLogRequest request) {

        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "loginDate");
        Pageable pageable = PageRequest.of(request.getPage() - 1, request.getLimit(), sort);

        Query query = new Query();
        if (StrUtil.isNotEmpty(request.getUserName())) {
            Pattern pattern = Pattern.compile("^.*" + request.getUserName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("userName").regex(pattern));
        }
        if (StrUtil.isNotEmpty(request.getIp())) {
            Pattern pattern = Pattern.compile("^.*" + request.getIp() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("ip").regex(pattern));
        }
        if (StrUtil.isNotEmpty(request.getLoginDate())) {
            Pattern pattern = Pattern.compile("^.*" + request.getLoginDate() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("loginDate").regex(pattern));
        }

        //获取总条数
        long count = mongoTemplate.count(query, LoginLogs.class);
        List<LoginLogs> logs = mongoTemplate.find(query.with(pageable), LoginLogs.class);

        return ResultUtil.page(logs, count);
    }

}
